
package com.dps.omc.action;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.omc.email.JobEmailService;
import com.dps.omc.enumer.EnumGroupType;
import com.dps.omc.enumer.EnumJobAuditState;
import com.dps.omc.enumer.EnumJobState;
import com.dps.omc.enumer.EnumTeam;
import com.dps.omc.model.*;
import com.dps.omc.publish.JobManager;
import com.dps.omc.publish.JobRunThread;
import com.dps.omc.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import com.dps.common.utils.IdGenerator;
import com.dps.common.utils.JsonResult;
import com.dps.common.utils.PageParam;
import com.dps.common.utils.Constants;

@Controller
public class JobAction extends AbstractAdminController<IJobService>{

    @Autowired
    private IJobService jobService;
    @Autowired
    private ITemplateShellService templateShellService;
    @Autowired
    private IGroupTypeService groupTypeService;
    @Autowired
    private IBizTypeService bizTypeService;
    @Autowired
    private IBizUnitService bizUnitService;
    @Autowired
    private JobManager jobManager;
    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private ISubjectArtifactService subjectArtifactService;
    @Autowired
    private ISubjectBizUnitService subjectBizUnitService;
    @Autowired
    private ISubjectBizTypeService subjectBizTypeService;
    @Autowired
    private IArtifactService artifactService;
    @Autowired
    private ITemplateTypeService templateTypeService;
    @Autowired
    private IJobBizUnitService jobBizUnitService;
    @Autowired
    private IJobBizTypeService jobBizTypeService;
    @Autowired
    private IJobArtifactService jobArtifactService;
    @Autowired
    private JobEmailService jobEmailService;
    
    @RequestMapping(value="/job/list")
    public String list(Job job, ModelMap model, PageParam pageParam, HttpServletRequest request, HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(job); 	
    	BizData4Page<Job> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("job", job);
    	return "/module/job/list";
    }

    @RequestMapping(value="/job/listaudit")
    public String listAudit(Job job,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
        Map<String, Object> conditions = getQueryMap(job);
        conditions.put("auditState",EnumJobAuditState.AUDIT_WAIT);
        BizData4Page<Job> pageCtx = doPage(model, conditions, pageParam);
        model.addAttribute("job", job);
        return "/module/job/listaudit";
    }

    @RequestMapping(value="/job/listbymanager")
    public String listByManager(Job job,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
        User user = getCurrentUser();
        Map<String, Object> conditions = getQueryMap(job);
        conditions.put("createrId",user.getId());
        BizData4Page<Job> pageCtx = doPage(model, conditions, pageParam);
        model.addAttribute("job", job);
        return "/module/job/listbymanager";
    }

    //作业详情弹框
    /*@RequestMapping(value="/job/jobdetail")
    public String jobdetail(String jobId,Job job,ModelMap model,PageParam pageParam,HttpServletRequest request,HttpServletResponse response){

        //获取参数
        Map<String, Object> conditions = getQueryMap(job);
        conditions.put("jobId",jobId);
        BizData4Page<Job> pageCtx = doPage(model, conditions, pageParam);
        model.addAttribute("job", job);
        return "/module/job/jobdetail";
    }*/

    /*@RequestMapping(value="/job/jobdetail")
    public String jobdetail(String jobId,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        //获取参数
        Job job = jobService.fetch(jobId);
        model.addAttribute("job",job);
        return "/module/subject/jobdetail";
    }*/


    @RequestMapping(value="/job/createbysubject")
    public String createBySubject(String subjectId,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<TemplateShell> templateShells = templateShellService.findAll();
        List<GroupType> groupTypes = groupTypeService.findAll();
//        List<BizType> bizTypes = bizTypeService.findAll();
//        List<BizUnit> bizUnits = bizUnitService.findAll();
        User user = getCurrentUser();
        List<BizType> bizTypes = bizTypeService.findListByUserRights(user.getId());
        List<BizUnit> bizUnits = bizUnitService.findListByUserRights(user.getId());

        List<SubjectBizUnit> subjectBizUnits = subjectBizUnitService.findList("subjectId",subjectId);
        List<SubjectBizType> subjectBizTypes = subjectBizTypeService.findList("subjectId",subjectId);
        Map<String,Object> condition = new HashMap<>();
        condition.put("subjectId",subjectId);
        condition.put("isDeploy",true);
        List<SubjectArtifact> subjectArtifacts = subjectArtifactService.queryList(condition,"seq","asc");
//        List<SubjectArtifact> subjectArtifacts = subjectArtifactService.findList("subjectId",subjectId);
        List<Artifact> artifacts = new ArrayList<>();
        for(SubjectArtifact subjectArtifact:subjectArtifacts)
        {
            Artifact artifact = artifactService.fetch(subjectArtifact.getArtifactId());
            artifacts.add(artifact);
        }
        model.addAttribute("artifacts", artifacts);
        model.addAttribute("typeTree", templateTypeService.getTypeTree());
        model.addAttribute("templateShells", templateShells);
        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("bizUnits", bizUnits);

        model.addAttribute("subjectId", subjectId);

        model.addAttribute("subjectBizUnitMap",this.getSubjectBizUnitMap(subjectBizUnits));
        model.addAttribute("subjectBizTypeMap",this.getSubjectBizTypeMap(subjectBizTypes));

        model.addAttribute("job", new Job(subjectId));
        return "module/job/editbysubject";
    }

    private Map<String,String> getSubjectBizUnitMap(List<SubjectBizUnit> subjectBizUnits)
    {
        Map<String,String> map = new HashMap<>();
        for(SubjectBizUnit subjectBizUnit:subjectBizUnits)
        {
            map.put(subjectBizUnit.getBizUnit(),subjectBizUnit.getBizUnit());
        }
        return map;
    }

    private Map<String,String> getSubjectBizTypeMap(List<SubjectBizType> subjectBizTypes)
    {
        Map<String,String> map = new HashMap<>();
        for(SubjectBizType subjectBizType:subjectBizTypes)
        {
            map.put(subjectBizType.getBizType(),subjectBizType.getBizType());
        }
        return map;
    }

    @RequestMapping(value="/job/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<TemplateShell> templateShells = templateShellService.findAll();
        List<GroupType> groupTypes = groupTypeService.findAll();
        List<BizType> bizTypes = bizTypeService.findAll();
        List<BizUnit> bizUnits = bizUnitService.findAll();
        model.addAttribute("templateShells", templateShells);
        model.addAttribute("groupTypes", groupTypes);
        model.addAttribute("bizTypes", bizTypes);
        model.addAttribute("bizUnits", bizUnits);

    	model.addAttribute("job", new Job());
        return "module/job/edit";
    }    
    
    @RequestMapping(value="/job/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){
    	
    	Job job = jobService.fetch(id);
    	model.addAttribute("job", job);
        return "module/job/edit";
    }    
    
    @RequestMapping(value="/job/save")
    @ResponseBody
    public String save(HttpServletRequest request,Job job,Boolean isTimer,Date[] planDateArray){
        User user = getCurrentUser();
		boolean isAddNew = StringUtils.isBlank(job.getId())?true:false;
        String[] bizUnitArray = request.getParameterValues("bizUnitArray");
        String[] bizTypeArray = request.getParameterValues("bizTypeArray");
        String[] artifactIdArray = request.getParameterValues("jobArtfactId");
        String[] artifactGroupTypeArray = request.getParameterValues("artifactGroupType");
        String[] artfactBizTypeArray = request.getParameterValues("artfactBizType");
//        String[] templateIdArray = request.getParameterValues("templateShell.id");
        String[] templateIdArray = request.getParameterValues("templateShellId");
        String preScriptIdArray = request.getParameter("preScript.id");

        if(isAddNew)
        {
            job.setId(IdGenerator.createNewId());
            job.setStatus(EnumJobState.NEW);
            job.setAuditState(EnumJobAuditState.AUDIT_NEW);
//            job.setIscron(false);
            job.setIscron(isTimer);
            job.setIsuploadfile(true);
            job.setCreaterId(user.getId());
            job.setCreaterName(user.getRealName());

            TemplateShell templateShell = templateShellService.fetch(job.getTemplateId());
            List<String> bizTypes = new ArrayList<String>();
            List<String> bizUnits = new ArrayList<String>();
            List<JobArtifact> jobArtifacts = new ArrayList<JobArtifact>();
            List<String> preScriptIds = new ArrayList<String>();
            Map<String,Date> planDateMap = new HashMap<>();
//            for(String bizUnit:bizUnitArray)
//            {
//                bizUnits.add(bizUnit);
//                planDateMap
//            }
            for(int i=0;i<bizUnitArray.length;i++)
            {
                bizUnits.add(bizUnitArray[i]);
                if(isTimer)
                {
                    planDateMap.put(bizUnitArray[i],planDateArray[i]);
                }
            }
            for(String bizType:bizTypeArray)
            {
                bizTypes.add(bizType);
            }
            if(StringUtils.isNotBlank(preScriptIdArray))
            {
                String[] arr = preScriptIdArray.split(",");
                for(String preScriptId:arr)
                {
                    preScriptIds.add(preScriptId);
                }
            }

            for(int i = 0;i<artifactIdArray.length;i++)
            {
                String artifactId = artifactIdArray[i];
                String groupType = artifactGroupTypeArray[i];
                String templateId = templateIdArray[i];
                String bizType = artfactBizTypeArray[i];
                JobArtifact jobArtifact = new JobArtifact();
                jobArtifact.setArtifactId(artifactId);
                jobArtifact.setTemplateId(templateId);
                jobArtifact.setGroupType(EnumGroupType.valueOf(groupType));
                jobArtifact.setBizType(bizType);

                jobArtifacts.add(jobArtifact);
            }
            jobManager.createNew(job,bizTypes,bizUnits,jobArtifacts,preScriptIds,planDateMap,user);
//            jobManager.create(job,bizTypes,bizUnits,templateShell);
        }
        else
        {
            jobService.update(job,user);
        }

        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }

    @RequestMapping(value="/job/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	jobService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }

    @RequestMapping(value="/job/run")
    @ResponseBody
    public String run(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
//        jobManager.run(job);
        new Thread(new JobRunThread(jobManager,job,user)).start();//异步执行
        return JsonResult.operateSuccess("listTask").toString();
    }

    @RequestMapping(value="/job/submitaudit")
    @ResponseBody
    public String submitAudit(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
        job.setAuditState(EnumJobAuditState.AUDIT_WAIT);
        jobService.update(job,user);
        return JsonResult.operateSuccess("listTask").toString();
    }

    //标准模板运行
    @RequestMapping(value="/job/runtest")
    @ResponseBody
    public String runTest(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
        jobManager.runByTeam(job, EnumTeam.TEST,EnumJobState.EXEC_TEST,user);

        return JsonResult.operateSuccess("listTask").toString();
    }

    //标准模板运行
    @RequestMapping(value="/job/runstandard")
    @ResponseBody
    public String runStandard(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
        jobManager.runByTeam(job, EnumTeam.STANDARD,EnumJobState.EXEC_STANDARD,user);

        return JsonResult.operateSuccess("listTask").toString();
    }

    @RequestMapping(value="/job/toaudit")
    public String toAudit(String id,HttpServletRequest request,ModelMap model) throws Exception {

        Job job = jobService.fetch(id);
        List<JobBizUnit> jobBizUnits = jobBizUnitService.findList("jobId",job.getId());
        List<JobArtifact> jobArtifacts = jobArtifactService.findList("jobId",job.getId());

        model.addAttribute("job",job);
        model.addAttribute("jobBizUnits",jobBizUnits);
        model.addAttribute("jobArtifacts",jobArtifacts);
        return "module/job/audit";
    }

    @RequestMapping(value="/job/audit")
    @ResponseBody
    public String audit(String id,EnumJobAuditState jobAuditState,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
        job.setAuditState(jobAuditState);
        jobService.update(job,user);
        jobEmailService.sendByAuditState(job);
        return JsonResult.operateSuccessClose(Constants.MAIN_TAB).toString();
    }

    @RequestMapping(value="/job/cancel")
    @ResponseBody
    public String cancel(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Job job = jobService.fetch(id);
        job.setStatus(EnumJobState.CANCEL);
        jobService.update(job,user);
        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    @RequestMapping(value="/job/detail")
    public String detail(String jobId,HttpServletRequest request,ModelMap model) throws Exception {

        Job job = jobService.fetch(jobId);
        List<JobBizType> jobBizTypes = jobBizTypeService.findList("jobId",job.getId());
        List<JobBizUnit> jobBizUnits = jobBizUnitService.findList("jobId",job.getId());
        List<JobArtifact> jobArtifacts = jobArtifactService.findList("jobId",job.getId());

        model.addAttribute("job",job);
        model.addAttribute("jobBizTypes",jobBizTypes);
        model.addAttribute("jobBizUnits",jobBizUnits);
        model.addAttribute("jobArtifacts",jobArtifacts);
        return "module/job/detail";
    }

    protected Map getQueryMap(Job job)
    {
    	Map<String, Object> conditions = new HashMap();
    	
		conditions.put("name", job.getName());		
		conditions.put("note", job.getNote());		
		conditions.put("groupType", job.getGroupType());		
		conditions.put("status", job.getStatus());		
		conditions.put("templateId", job.getTemplateId());		
		conditions.put("iscron", job.getIscron());		
		conditions.put("cronexpr", job.getCronexpr());		
		conditions.put("isuploadfile", job.getIsuploadfile());		
		conditions.put("artifactId", job.getArtifactId());		
		conditions.put("artifactPath", job.getArtifactPath());		
		conditions.put("createrId", job.getCreaterId());		
		conditions.put("createrName", job.getCreaterName());		
		conditions.put("createDate", job.getCreateDate());		
    	return conditions;
    }

    @Override
    protected IJobService getMainService() {
        return jobService;
    }

    @Override
    protected String getMainObjName() {
        return "job";
    }

    @Override
    protected String getViewTitle() {
        return "job";
    }
}
